package yeh.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import yeh.service.UserService;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LoginAspect {
    @Autowired
    private UserService userService;
    @Pointcut("execution(* *..UserServiceImpl.Login(..))")
    public void loginPointcut() {}

    @AfterReturning(value = "loginPointcut()", returning = "result")
    public void logLogin(JoinPoint joinPoint, Object result) {
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
        Object[] args = joinPoint.getArgs();
        String username = (String) args[0];

        System.out.println("ip"+ip);
        System.out.println("username"+username);

        userService.saveLog(username, ip,new Date());
    }
}
